/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import process from '@ohos.process'
import fs, { ReadOptions } from '@ohos.file.fs'
import util from '@ohos.util';

export class MemInfoUtils {
  private path = "/proc/" + process.pid + "/statm";
  constructor() {
  }

  public GetRss(): bigint
  {
    let bufSize = 64
    let space = 32
    let page = 4n
    let file = fs.openSync(this.path, fs.OpenMode.READ_ONLY)
    let buf = new ArrayBuffer(bufSize)
    let readOption : ReadOptions = {
      offset: 0,
      length: bufSize
    }

    let len = fs.readSync(file.fd, buf, readOption)
    fs.closeSync(file)

    let firstSpace: number = -1
    let secondSpace: number = -1
    let uint8Array = new Uint8Array(buf, 0, len)
    for (let i = 0; i < len; i++) {
      if (uint8Array[i] == space) {
        if (firstSpace == -1) {
          firstSpace = i + 1
          continue
        }
        if (secondSpace == -1) {
          secondSpace = i
          break
        }
      }
    }
    let actArray = uint8Array.slice(firstSpace, secondSpace)
    let decoder = util.TextDecoder.create()
    let str = decoder.decodeToString(actArray)
    return BigInt(str) * page
  }
}
